package com.sdkj.fixed.asset.assets.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.*;
import com.sdkj.fixed.asset.api.assets.out_vo.*;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.JpushClientUtil;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.*;
import com.sdkj.fixed.asset.pojo.system.PushManagement;
import com.sdkj.fixed.asset.pojo.system.UserManagement;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.List;
import java.util.*;

/**
 * @Author zhangjinfei
 * @Description //TODO 资产盘点
 * @Date 2020/7/21 10:54
 */
@Service
public class InventoryService extends BaseService<Inventory> {

    private final Logger log = LoggerFactory.getLogger(InventoryService.class);
    @Resource
    private InventoryMapper mapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private AssetIntermediateMapper assetIntermediateMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ScrapService scrapService;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private AssetLogMapper assetLogMapper;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private AssetReportMapper assetReportMapper;
    @Autowired
    private PushManagementMapper pushMapper;
    @Autowired
    private AssetReportService assetReportService;


    @Override
    public BaseMapper getMapper() {
        return mapper;
    }

    /**
     * 删除盘点任务
     * @param id
     */
    public void delete(String id){
//        String token = request.getHeader("token");
//        LoginUser loginUser = cacheUtils.getUser(token);
//        String userId = loginUser.getUserId();
//        Inventory inventory = new Inventory();
//        inventory.setInventoryId(id);
//        inventory.setIsDelete(1);
//        inventory.setUpdateTime(DateTools.nowDate());
//        inventory.setUpdateUser(userId);
//        mapper.updateByPrimaryKeySelective(inventory);
        mapper.deleteByPrimaryKey(id);

        Example example = new Example(AssetIntermediate.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("inventoryId", id);
//        AssetIntermediate ate = new AssetIntermediate();
//        ate.setIsDelete(1);
//        ate.setUpdateTime(DateTools.nowDate());
//        ate.setUpdateUser(userId);
//        assetIntermediateMapper.updateByExampleSelective(ate, example);
        assetIntermediateMapper.deleteByExample(example);
    }

    /**
     * 新增
     * @param inventory
     * @return
     */
    public Inventory add(Inventory inventory){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        //盘点单名称唯一校验
        Example example = new Example(Inventory.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("inventoryName", inventory.getInventoryName());
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDelete", 0);
        int count = mapper.selectCountByExample(example);
        if(count > 0){
            throw new LogicException("盘点名称已存在");
        }

        inventory.setState("0");
        inventory.setCreateTime(TimeTool.getCurrentTimeStr());
        inventory.setCreateUser(userId);
        inventory.setUpdateTime(TimeTool.getCurrentTimeStr());
        inventory.setUpdateUser(userId);
        inventory.setIsDelete(0);
        inventory.setOrgId(orgId);
        inventory.setAdminUserName(userName);


        //根据条件查询资产，生成盘点内容
        WarehousePagesParam warehouse = new WarehousePagesParam();
        warehouse.setOrgId(orgId);//机构
        Boolean flag = true;
        // redis 查询用户权限： 如果是管理员为false 查询全部
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            flag = false;
        }
        if(flag) {
            // 查询公司
            String companyType = "1";
            List<String> companyList = warehouseMapper.queryRelationIdLists(userId, companyType);
            //资产类别
            String classType = "2";
            List<String> classList = warehouseMapper.queryRelationIdLists(userId, classType);
            // 查询区域
            String areaType = "3";
            List<String> areaList = warehouseMapper.queryRelationIdLists(userId, areaType);
            if((companyList==null || companyList.size()==0) || (classList==null || classList.size()==0) ||  (areaList==null || areaList.size()==0) ){
                throw new LogicException("没有找到相应资产");
            }
        }

        if(StringUtils.isNotBlank(inventory.getAreaId())){
            warehouse.setAreaList( Arrays.asList(inventory.getAreaId().split(",")));//区域
        } else if (flag){
            warehouse.setAreaList(warehouseMapper.queryRelationIdLists(userId, "3"));
        }
        if(StringUtils.isNotBlank(inventory.getSetClassId())){
            warehouse.setClassList(Arrays.asList(inventory.getSetClassId().split(",")));//分类
        } else if (flag){
            warehouse.setClassList(warehouseMapper.queryRelationIdLists(userId, "2"));
        }
        if(StringUtils.isNotBlank(inventory.getCompanyId())){
            warehouse.setCompanyList(Arrays.asList(inventory.getCompanyId().split(",")));//所属公司
        } else if (flag){
            warehouse.setCompanyList(warehouseMapper.queryRelationIdLists(userId, "1"));
        }

        if(StringUtils.isNotBlank(inventory.getUseCompanyDeptId())){
            warehouse.setUseCompanyDeptList(Arrays.asList(inventory.getUseCompanyDeptId().split(",")));//使用公司和部门
        }
        warehouse.setPurchaseTimeStart(inventory.getPurchaseTimeStart());
        warehouse.setPurchaseTimeEnd(inventory.getPurchaseTimeEnd());
        if(inventory.getIsTransfer() == 0){
            warehouse.setState("8");
        }
        List<WarehouseResult> list = warehouseMapper.queryPages(warehouse);

        if(list == null || list.size()<=0){
            throw new LogicException("没有找到相应资产");
        }
        mapper.insertSelective(inventory);
        //插入盘点明细表
        list.stream().forEach(e ->{
            AssetIntermediate intermediate = new AssetIntermediate();
            intermediate.setInventoryId(inventory.getInventoryId());
            intermediate.setAssetId(e.getAssetId());
            intermediate.setAssetCode(e.getAssetCode());
            intermediate.setAssetName(e.getAssetName());
            intermediate.setSnNumber(e.getSnNumber());
            intermediate.setUnitMeasurement(e.getUnitMeasurement());
            intermediate.setStorageLocation(e.getStorageLocation());
            intermediate.setRemark(e.getRemark());
            intermediate.setPhoto(e.getPhoto());
            intermediate.setAssetClassId(e.getAssetClassId());
            intermediate.setAssetClassName(e.getAssetClassName());
            intermediate.setStandardModel(e.getStandardModel());
            intermediate.setSpecificationModel(e.getSpecificationModel());
            intermediate.setCompany(e.getCompany());
            intermediate.setCompanyName(e.getCompanyName());
            intermediate.setUseCompany(e.getUseCompany());
            intermediate.setUseCompanyName(e.getUseCompanyName());
            intermediate.setUseDepartment(e.getUseDepartment());
            intermediate.setUseDepartmentName(e.getUseDeptName());
            intermediate.setHandlerUserId(e.getHandlerUserId());
            intermediate.setHandlerUser(e.getHandlerUser());
            intermediate.setInventoryState("0");
            intermediate.setCreateTime(TimeTool.getCurrentTimeStr());
            intermediate.setCreateUser(userId);
            intermediate.setUpdateTime(TimeTool.getCurrentTimeStr());
            intermediate.setUpdateUser(userId);
            intermediate.setIsDelete(0);
            intermediate.setInventoryUser("");
            intermediate.setArea(e.getArea());
            intermediate.setAreaName(e.getAreaName());
            intermediate.setAssetState(e.getState());
            assetIntermediateMapper.insertSelective(intermediate);
        });


        //查询盘点表，全员盘点，
        String[] asia = {};
        if(inventory.getIsAllUser() == 1){
            asia = mapper.getInvUser(inventory.getInventoryId(), null);
        }
        if(inventory.getIsAllUser() == 0){
            asia = inventory.getUsername().split(",");
        }
        //推送盘点任务消息
        String notification_title = "资产盘点";
        String msg_title = "资产盘点";
        String msg_content = "您有资产盘点任务，请处理，盘点单名称："+ inventory.getInventoryName();
        log.info("创建资产盘点,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");

        Arrays.asList(asia).stream().forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(msg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });
        return inventory;
    }

    /**
     * 查看盘点信息
     * @param id
     */
    public Inventory queryInvInfo(String id){
        Inventory inventory = mapper.selectByPrimaryKey(id);
//        System.out.println(Arrays.asList(inventory.getUsername().split(",")));
        List<String> userNameList = mapper.userNameList(Arrays.asList(inventory.getUsername().split(",")));
        inventory.setUsername(StringUtils.join(userNameList.toArray(),","));
        return inventory;
    }


    /**
     * 分页查询
     * @param pageParams
     * @return
     */
    public List<InventoryExtend> getAllPage(PageParams<StateParam> pageParams){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        PageHelper.startPage(pageParams.getCurrentPage(), pageParams.getPerPageTotal());
        return mapper.getAll(orgId, pageParams.getParams().getState(), null, userId);
    }
    /**
     * 盘点任务统计数量
     * @return
     */
    public StateNum stateNum(){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        return mapper.stateNum(orgId, userId);
    }

    /**
     * 导出盘点任务列表
     * @return
     */
    public List<InventoryExtend> export(String orgId, String state, String token){
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        return mapper.getAll(orgId, state, null, userId);
    }

    /**
     * 分配用户
     * @param inventory
     */
    public void allotUser(Inventory inventory){
        mapper.updateByPrimaryKeySelective(inventory);
    }

    /**
     * 盘点结果-分页查询
     * @param pageParams
     * @return
     */
    public List<AssetIntermediate> queryInvResult(PageParams<AssetIntermediate> pageParams){
        Example example = new Example(AssetIntermediate.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("inventoryId", pageParams.getParams().getInventoryId());
        criteria.andEqualTo("isDelete", 0);
        if(StringUtils.isNotBlank(pageParams.getParams().getInventoryState())){
            criteria.andEqualTo("inventoryState", pageParams.getParams().getInventoryState());
        }
        PageHelper.startPage(pageParams.getCurrentPage(), pageParams.getPerPageTotal());
        return assetIntermediateMapper.selectByExample(example);
    }

    /**
     * 盘点结果-统计数量
     * @param inventoryId
     * @return
     */
    public InventoryStateNum resultStatistical(String inventoryId){
        return mapper.invResultNum(inventoryId);
    }

    /**
     * 查询未盘点的用户
     * @param pageParams
     * @return
     */
    public List<UserInfo> queryNoInvUserInfo(PageParams<Search> pageParams){
        PageHelper.startPage(pageParams.getCurrentPage(), pageParams.getPerPageTotal());
        return mapper.getNoInvUserInfo( pageParams.getParams().getInventoryId(), pageParams.getParams().getSearch());
    }

    /**
     * 添加盘盈
     * @param intermediate
     * @return
     */
    public AssetIntermediate addInvSurplus(AssetIntermediateExtend intermediate){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        String companyNo = intermediate.getCompanyNo();
        String classNo = intermediate.getAssetClassNo();
        String areaNo = intermediate.getAreaNo();
        String strDate = DateTools.nowDayStr();
        Long increment = redisUtil.getIncr("ZCRK_"+companyNo+classNo+areaNo+strDate,System.currentTimeMillis()/1000);
        String no = String.format("%04d",Long.valueOf(increment));

//        公司编码（4）-资产分类（4）-区域（4位）-生成年月日（8位）示例：20200714-流水号4位
        intermediate.setAssetCode(companyNo+classNo+areaNo+strDate+no);
        intermediate.setInventoryState("2");
        intermediate.setCreateTime(TimeTool.getCurrentTimeStr());
        intermediate.setCreateUser(userId);
        intermediate.setUpdateTime(TimeTool.getCurrentTimeStr());
        intermediate.setUpdateUser(userId);
        intermediate.setIsDelete(0);
        intermediate.setChangeCompanyTreecode(intermediate.getChangeCompanyTreecode());
        intermediate.setChangeUseCompanyTreecode(intermediate.getChangeUseDeptTreecode());
        intermediate.setChangeUseDeptTreecode(intermediate.getChangeUseDeptTreecode());

        if(StringUtils.isNotBlank(intermediate.getChangeHandlerUser())){
            UserInfo user = assetReportMapper.selectUser(intermediate.getChangeHandlerUser());
            intermediate.setChangeUseCompany(user.getCompanyId());
            intermediate.setChangeUseDepartment(user.getDeptId());
            intermediate.setChangeUseCompanyName(user.getCompanyName());
            intermediate.setChangeUseDepartmentName(user.getDeptName());
            intermediate.setChangeUseCompanyTreecode(user.getCompanyTreecode());
            intermediate.setChangeUseDeptTreecode(user.getDeptTreecode());
        }
        assetIntermediateMapper.insertSelective(intermediate);
        return intermediate;
    }

    /**
     * 给未盘点的用户推送消息提醒
     * @param ids
     */
    public void pushNoInvUser(String ids){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String[] asia = ids.split(",");
        String notification_title = "资产盘点";
        String msg_title = "资产盘点";
        String msg_content = "您有资产盘点任务，请处理";
        log.info("未盘点资产,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");

        Arrays.asList(ids.split(",")).stream().forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(msg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });
    }

    /**
     * 盘点结果-导出
     * @param id
     * @return
     */
    public List<AssetIntermediate> exportInvResult(String id){
        Example example = new Example(AssetIntermediate.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("inventoryId", id);
        return assetIntermediateMapper.selectByExample(example);
    }
    /**
     * 盘点结果-提交盘点结果
     * @param param
     * @return
     */
    public void submitInvResult(SubInvResultParam param){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userName = loginUser.getUserName();
        String userId = loginUser.getUserId();


        //盘点结束
        Inventory inv = new Inventory();
        inv.setInventoryId(param.getInventoryId());
        inv.setState("1");
        mapper.updateByPrimaryKeySelective(inv);

//        查询盘点信息
        Example example = new Example(AssetIntermediate.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("inventoryId", param.getInventoryId());
        criteria.andEqualTo("isDelete", 0);
        List<AssetIntermediate> list = assetIntermediateMapper.selectByExample(example);

//        盘盈资产自动新增入库
        if(param.getAutoAddAsset() == 0){
            list.stream().forEach(f->{
                if("2".equals(f.getInventoryState())){
                    Warehouse warehouse = new Warehouse();
                    warehouse.setAssetCode(f.getAssetCode());
                    warehouse.setAssetName(f.getAssetName());
                    warehouse.setAssetClassId(f.getAssetClassId());
                    warehouse.setUnitMeasurement(f.getUnitMeasurement());
                    warehouse.setSpecificationModel(f.getSpecificationModel());
                    warehouse.setStandardModel(f.getStandardModel());
                    warehouse.setStorageLocation(f.getChangeStorageLocation());
                    warehouse.setArea(f.getChangeArea());
                    warehouse.setCompany(f.getCompany());
                    warehouse.setUseCompany(f.getChangeUseCompany());
                    warehouse.setUseDepartment(f.getChangeUseDepartment());
                    warehouse.setHandlerUserId(f.getChangeHandlerUser());
                    warehouse.setHandlerUser(f.getChangeHandlerUserName());
                    warehouse.setUseCompanyTreecode(f.getChangeUseCompanyTreecode());
                    warehouse.setUseDeptTreecode(f.getChangeUseDeptTreecode());
                    if(StringUtils.isNotBlank(f.getChangeHandlerUser())){
                        UserInfo user = assetReportMapper.selectUser(f.getChangeHandlerUser());
                        warehouse.setState("在用");
                        warehouse.setUseCompany(user.getCompanyId());
                        warehouse.setUseDepartment(user.getDeptId());
                    } else {
                        warehouse.setState("闲置");
                    }
                    warehouse.setPhoto(f.getPhoto());
                    warehouse.setRemark(f.getRemark());
                    warehouse.setOrgId(orgId);
                    warehouse.setCreateTime(DateTools.nowDate());
                    warehouse.setCreateUser(userId);
                    warehouse.setUpdateTime(DateTools.nowDate());
                    warehouse.setUpdateUser(userId);
                    warehouse.setIsDelete(0);
                    warehouse.setAdminId(userId);
                    warehouse.setAdmin(userName);
                    warehouse.setPurchaseTime(DateTools.dateToString(new Date(), "yyyy-MM-dd"));
                    warehouseService.warehouseTotalNum(warehouse.getOrgId());
                    warehouseMapper.insertSelective(warehouse);

                    AssetLog assetLog = new AssetLog();
                    assetLog.setAssetId(warehouse.getAssetId());
                    assetLog.setLogType("盘点管理");
                    assetLog.setHandlerId(userId);
                    assetLog.setHandlerUser(userName);
                    assetLog.setHandlerContext("盘盈资产自动新增入库");
                    assetLog.setCreateUser(userId);
                    assetLog.setCreateTime(TimeTool.getCurrentTimeStr());
                    assetLogMapper.insertSelective(assetLog);

                    if(StringUtils.isNotBlank(f.getChangeHandlerUser())){
                        //添加资产使用记录
                        String[] split = DateTools.dateToString(new Date(),"yyyy-MM-dd").split("-");
                        AssetReport assetReport = new AssetReport();
                        assetReport.setAssetId(warehouse.getAssetId());
                        assetReport.setArYear(split[0]);
                        assetReport.setArMonth(split[1]);
                        assetReport.setArDay(split[2]);
                        assetReport.setUseType(2);
                        assetReport.setUseUserId(userId);
                        assetReportService.insertReport(assetReport);
                    }
                }

            });
        }
//        已盘资产修改内容自动更新资产信息
        if(param.getAutoUpdateAsset() == 0){
            list.stream().forEach(e->{
                boolean flag = (StringUtils.isNotBlank(e.getChangeArea())|| StringUtils.isNotBlank(e.getChangeHandlerUser()) ||
                        StringUtils.isNotBlank(e.getChangeUseCompany()) || StringUtils.isNotBlank(e.getChangeUseDepartment()) ||
                        StringUtils.isNotBlank(e.getChangeStorageLocation())) && "1".equals(e.getInventoryState());
                if(flag){
                    stateLog(e.getAssetId(), "盘点管理", e, userName, userId);

                    Warehouse warehouse = new Warehouse();
                    warehouse.setAssetId(e.getAssetId());
                    warehouse.setArea("".equals(e.getChangeArea()) ? null : e.getChangeArea());
                    warehouse.setStorageLocation("".equals(e.getChangeStorageLocation()) ? null : e.getChangeStorageLocation());
                    warehouse.setCompany("".equals(e.getCompany()) ? null : e.getCompany());
                    warehouse.setUseCompany("".equals(e.getChangeUseCompany()) ? null : e.getChangeUseCompany());
                    warehouse.setUseDepartment("".equals(e.getChangeUseDepartment()) ? null : e.getChangeUseDepartment());
                    warehouse.setHandlerUserId("".equals(e.getChangeHandlerUser()) ? null : e.getChangeHandlerUser());
                    warehouse.setHandlerUser("".equals(e.getChangeHandlerUserName()) ? null : e.getChangeHandlerUserName());
                    warehouse.setUpdateTime(TimeTool.getCurrentTimeStr());
                    warehouse.setUpdateUser(userId);
                    if(StringUtils.isNotBlank(e.getChangeHandlerUser())){
                        UserInfo user = assetReportMapper.selectUser(e.getChangeHandlerUser());
                        warehouse.setState("在用");
                        warehouse.setUseCompany(user.getCompanyId());
                        warehouse.setUseDepartment(user.getDeptId());

                        //添加资产使用记录
                        String[] split = DateTools.dateToString(new Date(),"yyyy-MM-dd").split("-");
                        AssetReport assetReport = new AssetReport();
                        assetReport.setAssetId(e.getAssetId());
                        assetReport.setArYear(split[0]);
                        assetReport.setArMonth(split[1]);
                        assetReport.setArDay(split[2]);
                        assetReport.setUseType(2);
                        assetReport.setUseUserId(userId);
                        assetReportService.insertReport(assetReport);
                    }
                    warehouseMapper.updateByPrimaryKeySelective(warehouse);
                }
            });
        }
//        未盘、盘亏资产自动清理报废
        if(param.getAutoScrap() == 0){
            List<String> ids = new ArrayList<>();
            list.stream().forEach(e->{
                if("闲置".equals(e.getAssetState()) && ("0".equals(e.getInventoryState()) || "3".equals(e.getInventoryState()))){
                    ids.add(e.getAssetId());
                }
            });
            if(ids.size()>0){
                ScrapExtend scrap = new ScrapExtend();
                scrap.setDate(DateTools.dateToString(new Date(), "yyyy-MM-dd"));
                scrap.setScrapUser(userName);
                scrap.setNote("未盘、盘亏闲置资产自动清理报废");
                scrap.setAssetIdList(ids);
                scrap.setReserved("盘点管理");
                scrapService.add(scrap);
            }

        }
    }
    /**
     * 删除盘盈
     * @param ids
     * @return
     */
    public void delInvSurplus(String ids){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        Example example = new Example(AssetIntermediate.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(ids.split(",")));
        AssetIntermediate ate = new AssetIntermediate();
        ate.setIsDelete(1);
        ate.setUpdateTime(TimeTool.getCurrentTimeStr());
        ate.setUpdateUser(userId);
        assetIntermediateMapper.updateByExampleSelective(ate, example);
    }

    /**
     * 保存修改盘盈
     * @param intermediate
     * @return
     */
    public void saveUpdInvResultByIds(AssetIntermediate intermediate){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        Example example = new Example(AssetIntermediate.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(intermediate.getId().split(",")));

        if(StringUtils.isNotBlank(intermediate.getChangeHandlerUser())){
            UserInfo user = assetReportMapper.selectUser(intermediate.getChangeHandlerUser());
            intermediate.setChangeUseCompany(user.getCompanyId());
            intermediate.setChangeUseDepartment(user.getDeptId());
            intermediate.setChangeUseCompanyName(user.getCompanyName());
            intermediate.setChangeUseDepartmentName(user.getDeptName());
        }
        AssetIntermediate ate = new AssetIntermediate();
        ate.setChangeArea(intermediate.getChangeArea());
        ate.setChangeAreaName(intermediate.getChangeAreaName());
        ate.setChangeUseCompany(intermediate.getChangeUseCompany());
        ate.setChangeUseCompanyName(intermediate.getChangeUseCompanyName());
        ate.setChangeUseDepartment(intermediate.getChangeUseDepartment());
        ate.setChangeUseDepartmentName(intermediate.getChangeUseDepartmentName());
        ate.setChangeHandlerUser(intermediate.getChangeHandlerUser());
        ate.setChangeHandlerUserName(intermediate.getChangeHandlerUserName());
        ate.setChangeStorageLocation(intermediate.getChangeStorageLocation());
        ate.setUpdateTime(TimeTool.getCurrentTimeStr());
        ate.setUpdateUser(userId);
        if(StringUtils.isBlank(intermediate.getRemark())){
            ate.setInventoryState("1");
        }
        ate.setRemark(intermediate.getRemark());
        ate.setChangeCompanyTreecode(intermediate.getChangeCompanyTreecode());
        ate.setChangeUseCompanyTreecode(intermediate.getChangeUseCompanyTreecode());
        ate.setChangeUseDeptTreecode(intermediate.getChangeUseDeptTreecode());
        ate.setInventoryUser(userName);
        assetIntermediateMapper.updateByExampleSelective(ate, example);
    }


    /**
     * 资产处理日志
     */
    public void stateLog(String assetId, String modelName, AssetIntermediate intermediate, String handlerUser, String handlerUserId){
        WarehouseResult warehouse = warehouseService.queryByAssetId(assetId);

        LogContext context = new LogContext();
        context.setBeforeareaName(warehouse.getAreaName());
        context.setBeforestorageLocation(warehouse.getStorageLocation());
        context.setBeforeuseCompanyName(warehouse.getUseCompanyName());
        context.setBeforeuseDepartmentName(warehouse.getUseDeptName());
        context.setBeforehandlerUserName(warehouse.getHandlerUser());
        context.setAfterareaName(intermediate.getChangeAreaName());
        context.setAfterstorageLocation(intermediate.getChangeStorageLocation());
        context.setAfteruseCompanyName(intermediate.getChangeUseCompanyName());
        context.setAfteruseDepartmentName(intermediate.getChangeUseDepartmentName());
        context.setAfterhandlerUserName(intermediate.getChangeHandlerUserName());
        String logContent = "资产【"+warehouse.getAssetName()+"】"+ modelName +"处置；" + ChangLogUtil.simpleLogContxt(context);
        AssetLog assetLog = new AssetLog();
        assetLog.setAssetId(assetId);
        assetLog.setLogType(modelName);
        assetLog.setHandlerId(handlerUserId);
        assetLog.setHandlerUser(handlerUser);
        assetLog.setHandlerContext(logContent);
        assetLog.setCreateUser(handlerUserId);
        assetLog.setCreateTime(TimeTool.getCurrentTimeStr());
        assetLogMapper.insertSelective(assetLog);
    }

    /**
     * app
     * 查询用户盘点任务
     * @return
     */
    public List<AppInvEntity> appInvList(AppInvSelParam param){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        List<AppInvEntity> list = mapper.queryInvList(orgId, userId, param.getInventoryState(), param.getSearch(), null);
        list.stream().forEach(e->{
            List<Inventory> invList = mapper.queryInvByAsset(orgId, userId, e.getAssetId(), param.getInventoryState(), null, null);
            e.setIsManual("0");
            Iterator<Inventory> it = invList.iterator();
            while (it.hasNext()){
                Inventory inventory = it.next();
                if(inventory.getIsManual() == 1){
                    e.setIsManual("1");
                }
                if(inventory.getIsAllUser() == 0 && StringUtils.isNotBlank(inventory.getUsername()) && !inventory.getUsername().contains(userId)){
                    it.remove();
                }
            }
            e.setInvList(invList);

        });
        //管理员分配用户
        UserManagement user = mapper.userInfo(userId);
        if("1".equals(user.getType())){
            List<AppInvEntity> list1 = mapper.queryInvList(orgId, null, param.getInventoryState(), param.getSearch(), null);
            list1.stream().forEach(e->{
                List<Inventory> invList = mapper.queryInvByAsset(orgId, null, e.getAssetId(), param.getInventoryState(), null, userId);
                e.setIsManual("0");
                Iterator<Inventory> it = invList.iterator();
                while (it.hasNext()){
                    Inventory inventory = it.next();
                    if(inventory.getIsManual() == 1){
                        e.setIsManual("1");
                    }
                    if(inventory.getIsAllUser() == 0 && StringUtils.isNotBlank(inventory.getUsername()) && !inventory.getUsername().contains(userId)){
                        it.remove();
                    }
                }
                e.setInvList(invList);
            });
            list.addAll(list1);
        }

        //去重
        Set<AppInvEntity> set = new HashSet<>(list);
        list  = new ArrayList<>(set);
        Iterator<AppInvEntity> it = list.iterator();
        while(it.hasNext()){
            List<Inventory> x = it.next().getInvList();
            if(CollectionUtils.isEmpty(x)){
                it.remove();
            }
        }

        return list;
    }
    /**
     * app
     * 根据盘点单查询用户盘点任务
     * @return
     */
    public AppInvOrder appInvOrder(AppInvSelParam param){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        Inventory t = mapper.selectByPrimaryKey(param.getInventoryId());
        if(t == null){
            return null;
        }
        if(t.getIsAllUser() == 0 && !t.getUsername().contains(userId)){
            return null;
        }
        if(t.getUsername().contains(userId)){
            userId = null;
        }
        AppInvOrder inv = mapper.invOrder(userId, param.getInventoryId());
        if(inv == null || StringUtils.isBlank(inv.getInventoryId())){
            return null;
        }
        List<AppInvEntity> list = mapper.queryInvList(orgId, userId, param.getInventoryState(), null, param.getInventoryId());
        inv.setAppInvEntityList(list);
        return inv;
    }
    /**
     * app
     * 员工提交盘点结果,手动和扫描盘点
     * @param params
     * @return
     */
    public void appUpdInvState(AppUpdInvState params){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();
        Example example = new Example(AssetIntermediate.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("inventoryId", Arrays.asList(params.getInventoryIds().split(",")));
        criteria.andEqualTo("assetCode", params.getAssetCode());
        AssetIntermediate ate = new AssetIntermediate();
        ate.setInventoryState(params.getInventoryState());
        ate.setRemark(params.getNote());
        ate.setUpdateTime(TimeTool.getCurrentTimeStr());
        ate.setUpdateUser(userId);
        ate.setInventoryUser(userName);
        assetIntermediateMapper.updateByExampleSelective(ate, example);
    }
    /**
     * app
     * 扫码枪盘点
     * @param param
     * @return
     */
    public void appSweepGunInv(SweepGunInvParam param){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();
        Example example = new Example(AssetIntermediate.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("inventoryId", param.getInventoryId());
        criteria.andIn("assetCode", param.getAssetCodeList());
//        criteria.andEqualTo("handlerUserId", userId);
        criteria.andEqualTo("inventoryState", "0");
        AssetIntermediate ate = new AssetIntermediate();
        ate.setInventoryState("1");
        ate.setRemark("扫码抢盘点");
        ate.setUpdateTime(TimeTool.getCurrentTimeStr());
        ate.setUpdateUser(userId);
        ate.setInventoryUser(userName);
        assetIntermediateMapper.updateByExampleSelective(ate, example);
    }

    /**
     * 下载
     * @param inventoryId
     * @throws IOException
     */
    public void download(String inventoryId) throws IOException {
        Inventory inv = queryInvInfo(inventoryId);
        InventoryStateNum num = resultStatistical(inventoryId);

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFCellStyle style_title = wb.createCellStyle();
        HSSFFont font_title = wb.createFont();
        font_title.setFontName("微软雅黑");// 设置字体
        font_title.setFontHeightInPoints((short) 20);// 设置字体大小
        font_title.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 设置字体加粗
        style_title.setFont(font_title);
        style_title.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 设置垂直居中
        style_title.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置文本居中

        HSSFCellStyle style_title_1 = wb.createCellStyle();
        HSSFFont font_title_1 = wb.createFont();
        font_title_1.setFontName("微软雅黑");// 设置字体
        font_title_1.setFontHeightInPoints((short) 12);
        font_title_1.setColor((short)40);
        font_title_1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 设置字体加粗
        style_title_1.setFont(font_title_1);
        style_title_1.setVerticalAlignment(HSSFCellStyle.VERTICAL_BOTTOM);// 设置垂直居中
        style_title_1.setAlignment(HSSFCellStyle.ALIGN_FILL);// 设置文本居中

        HSSFSheet sheet1 = wb.createSheet("资产盘点报告");
        ExcelStyle.printSetup(sheet1);
        HSSFRow row1 = null;
        HSSFCell cell1 = null;
        row1 = sheet1.createRow(0);
        row1.setHeight((short) 1000 );
        cell1 = row1.createCell(1);
        cell1.setCellValue(inv.getInventoryName()+"固定资产盘点报告");
        cell1.setCellStyle(style_title);
        sheet1.addMergedRegion(new CellRangeAddress(0, 0, 1, 7));

        sheet1.setColumnWidth(0, 252*10+323);
        sheet1.setColumnWidth(1, 252*35+323);
        sheet1.setColumnWidth(2, 252*35+323);

        String[] cellValueb = {"盘点时间：",inv.getCreateTime(),
                "盘点人：",inv.getUsername(),
                "盘点范围","",
                "购入时间范围：",inv.getPurchaseTimeStart()+" - "+inv.getPurchaseTimeEnd(),
                "使用公司和部门范围：",inv.getUseCompanyDeptName(),
                "所属公司范围：",inv.getCompanyName(),
                "资产分类范围：",inv.getSetClassName(),
                "区域范围：",inv.getAreaName(),
                "管理员范围：",inv.getAdminUserName(),
        };
        for (int i = 0; i < cellValueb.length; i++) {
            if(i % 2 == 0){
                row1 = sheet1.createRow(i/2 + 2);
                cell1 = row1.createCell(1);
                cell1.setCellValue(cellValueb[i]);
            }
            else {
                cell1 = row1.createCell(2);
                cell1.setCellValue(cellValueb[i]);
            }
            if(row1.getRowNum() == 4){
                cell1.setCellStyle(style_title_1);
                row1.setHeight((short) 500);
            }
        }

        row1 = sheet1.createRow(14);
        cell1 = row1.createCell(1);
        cell1.setCellValue("盘点情况概述");
        cell1.setCellStyle(style_title_1);
        row1.setHeight((short) 500);

        row1 = sheet1.createRow(15);
        cell1 = row1.createCell(1);
        cell1.setCellValue("1、盘点范围内共有资产："+ num.getInventoryStateNum() +"个；实盘资产："+ num.getInventoryStateNum_1()+"个；" +
                "未盘/盘亏资产："+(Long.valueOf(num.getInventoryStateNum_0())+Long.valueOf(num.getInventoryStateNum_3()))+"个；" +
                "盘盈资产："+ num.getInventoryStateNum_2()+"个");
        row1 = sheet1.createRow(34);
        cell1 = row1.createCell(1);
        cell1.setCellValue("2、 已盘资产中没有变动的资产有："+ Long.valueOf(num.getChangeStateNum_9())
                +"个；盘点时使用公司/使用部门/使用人变更的资产有："+ Long.valueOf(num.getChangeStateNum_4())
                +"个；区域/存放地点变更的资产有："+ Long.valueOf(num.getChangeStateNum_5()) +"个；");
        row1 = sheet1.createRow(54);
        cell1 = row1.createCell(1);
        if(Long.valueOf(num.getInventoryStateNum_1()) == 0){
            cell1.setCellValue( "3、已盘资产中，在用资产："+ Long.valueOf(num.getAssetStateNum_7()) +"个，闲置资产"+ Long.valueOf(num.getAssetStateNum_6())
                    +"个，借出资产"+ Long.valueOf(num.getAssetStateNum_8()) +"个，闲置率"
                    + 0 +"%。");
        }else{
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float)  Long.valueOf(num.getAssetStateNum_6()) / (float) Long.valueOf(num.getInventoryStateNum_1()) * 100);

            cell1.setCellValue( "3、已盘资产中，在用资产："+ Long.valueOf(num.getAssetStateNum_7()) +"个，闲置资产"+ Long.valueOf(num.getAssetStateNum_6())
                    +"个，借出资产"+ Long.valueOf(num.getAssetStateNum_8()) +"个，闲置率"
                    + result +"%。");
        }

        Font font = new Font("新宋体", Font.BOLD, 15);
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        Map<String, Double> map=new HashMap<String, Double>();
        map.put("实盘资产", Double.valueOf(num.getInventoryStateNum_1()));//名称，值
        map.put("未盘/盘亏资产", Double.valueOf(num.getInventoryStateNum_0())+Double.valueOf(num.getInventoryStateNum_3()));
        map.put("盘盈资产", Double.valueOf(num.getInventoryStateNum_2()));
        // 创建JFreeChart
        JFreeChart chart = ExcelUtils.createPort("资产盘点情况", map, font);
        // 读取chart信息至字节输出流
        ChartUtilities.writeChartAsPNG(byteArrayOut, chart, 600, 350);
        // 画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
        HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
        // anchor主要用于设置图片的属性
        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 1, (short) 17, (short) 4, (short) 32);
//        anchor.setAnchorType(3);
        // 插入图片
        patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));

        ByteArrayOutputStream byteArrayOut1 = new ByteArrayOutputStream();
        Map<String, Double> map1 = new HashMap<String, Double>();
        map1.put("没有变动的资产", Double.valueOf(num.getChangeStateNum_9()));//名称，值
        map1.put("盘点时使用公司/使用部门/使用人变更的资产", Double.valueOf(num.getChangeStateNum_4()));
        map1.put("区域/存放地点变更的资产", Double.valueOf(num.getChangeStateNum_5()));
        JFreeChart chart1 = ExcelUtils.createPort("资产变动情况", map1, font);
        ChartUtilities.writeChartAsPNG(byteArrayOut1, chart1, 600, 300);
        HSSFPatriarch patriarch1 = sheet1.createDrawingPatriarch();
        HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 0, 0, (short) 1, (short) 36, (short) 4, (short) 52);
        patriarch1.createPicture(anchor1, wb.addPicture(byteArrayOut1.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));

        ByteArrayOutputStream byteArrayOut2 = new ByteArrayOutputStream();
        Map<String, Double> map2 = new HashMap<String, Double>();
        map2.put("在用资产", Double.valueOf(num.getAssetStateNum_7()));//名称，值
        map2.put("闲置资产", Double.valueOf(num.getAssetStateNum_6()));
        map2.put("借出资产", Double.valueOf(num.getAssetStateNum_8()));
        JFreeChart chart2 = ExcelUtils.createPort("资产使用情况", map2, font);
        ChartUtilities.writeChartAsPNG(byteArrayOut2, chart2, 600, 300);
        HSSFPatriarch patriarch2 = sheet1.createDrawingPatriarch();
        HSSFClientAnchor anchor2 = new HSSFClientAnchor(0, 0, 0, 0, (short) 1, (short) 55, (short) 4, (short) 69);
        patriarch2.createPicture(anchor2, wb.addPicture(byteArrayOut2.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));

        HSSFSheet sheet2 = wb.createSheet("资产盘点情况明细表");
        HSSFRow row2 = null;
        HSSFCell cell2 = null;
        int rownum2 = 0;
        row2 = sheet2.createRow(rownum2++);
        String[] cellsName = {"盘点状态","资产图片","资产类别","SN号","条形码","资产名称","规格型号","计量单位","区域","存放地点",
                "使用公司","使用部门","所属公司","使用人","修改后区域","修改后存放地点","修改后使用公司","修改后使用部门",
                "修改后使用人","盘点人","盘点备注"};
        for (int i = 0; i < cellsName.length; i++) {
            cell2 = row2.createCell(i + 1);
            cell2.setCellValue(cellsName[i]);
            cell2.setCellStyle(ExcelStyle.styleCellName(wb));
        }
        List<AssetIntermediate> list = exportInvResult(inventoryId);
        //遍历数据
        for (AssetIntermediate ate : list) {
            row2 = sheet2.createRow(rownum2++);
            String inventoryState = ate.getInventoryState();
            switch (inventoryState) {
                case "0" :
                    inventoryState = "未盘";
                    break;
                case "1" :
                    inventoryState = "已盘";
                    break;
                case "2" :
                    inventoryState = "盘盈";
                    break;
                case "3" :
                    inventoryState = "盘亏";
                    break;
            }
            String[] cellValues = {inventoryState,ate.getPhoto(),ate.getAssetClassName(),ate.getSnNumber(),ate.getAssetCode(),ate.getAssetName(),ate.getStorageLocation(),
                    ate.getUnitMeasurement(),ate.getAreaName(),ate.getStorageLocation(),ate.getUseCompanyName(),ate.getUseDepartmentName(),ate.getCompanyName(),
                    ate.getHandlerUser(),ate.getChangeAreaName(),ate.getChangeStorageLocation(),ate.getChangeUseCompanyName(),ate.getChangeUseDepartmentName(),
                    ate.getChangeHandlerUserName(),ate.getInventoryUser(),ate.getRemark()};
            for (int i = 0; i < cellValues.length; i++) {
                cell2 = row2.createCell(i + 1);
                cell2.setCellValue(cellValues[i]);
                cell2.setCellStyle(ExcelStyle.styleCellValue(wb));
            }
        }

        // 输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition","attachment; filename="+
                URLEncoder.encode("盘点报告"+DateTools.dateToString(new Date(), "yyyyMMddHHmmss") + ".xlsx", "UTF-8"));    //filename =  文件名
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();

    }

}
